package go_im

import (
	"fmt"
	"net"
)

type User struct {
	Name   string
	Addr   string
	Ch     chan string
	conn   net.Conn
	server *Server
}

func NewUser(conn net.Conn, server *Server) *User {
	user := &User{
		Name:   conn.RemoteAddr().String(),
		Addr:   conn.RemoteAddr().String(),
		Ch:     make(chan string),
		conn:   conn,
		server: server,
	}

	//启动监听当前用户给chan发送的消息
	go user.ListenMessage()
	return user
}

func (user *User) ListenMessage() {
	for {
		msg := <-user.Ch
		msg = msg + "\n"
		_, err := user.conn.Write([]byte(msg))
		if err != nil {
			fmt.Println("write error:" + err.Error())
			user.Offline()
			return
		}
	}
}

func (user *User) SendMessage(message string) {
	_, err := user.conn.Write([]byte(message))
	if err != nil {
		return
	}
}

func (user *User) DoMessage(msg string) {

	if msg == "who is your daddy" {
		var specMsg string
		user.server.mapLock.Lock()
		for _, cli := range user.server.OnlineMap {
			specMsg += cli.Name + "在线 \n"
		}
		user.server.mapLock.Unlock()
		_, err := user.conn.Write([]byte(specMsg))
		if err != nil {
			fmt.Println("write error:" + err.Error())
			return
		}
	} else if len(msg) > 7 && msg[:7] == "rename|" {
		newName := msg[7:]

		_, ok := user.server.OnlineMap[newName]
		if ok {
			_, err := user.conn.Write([]byte("用户名已经被占用: " + newName + "\n"))
			if err != nil {
				fmt.Println("用户名修改失败,write error:" + err.Error())
			}
			return
		}

		user.server.mapLock.Lock()
		delete(user.server.OnlineMap, user.Name)
		user.server.OnlineMap[newName] = user
		user.server.mapLock.Unlock()
		user.Name = newName
		_, err := user.conn.Write([]byte("修改用户名成功: " + newName + "\n"))
		if err != nil {
			fmt.Println("用户名修改失败,write error:" + err.Error())
			return
		}
	} else {
		user.server.BroadCast(user, msg)
	}

}

func (user *User) Online() {
	user.server.mapLock.Lock()
	user.server.OnlineMap[user.Name] = user
	user.server.mapLock.Unlock()

	//广播上线消息
	user.server.BroadCast(user, "上线啦")
}

func (user *User) Offline() {
	user.server.mapLock.Lock()
	delete(user.server.OnlineMap, user.Name)
	user.server.mapLock.Unlock()
	user.server.BroadCast(user, "下线啦")

	//close(user.Ch)
	//err := user.conn.Close()
	//if err != nil {
	//	return
	//}
}
